/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import { PullToRefresh, ListView, Modal, Toast } from 'antd-mobile';
import ReactDOM from 'react-dom';
import { connect, history } from 'umi';
import scrollAnimation from '@/utils/scrollAnimation';
import LoadingFooter from '../LoadingFooter';
import { getFetch, putFetch } from '@/utils/doFetch';
import moment from 'moment';
import { Drawer, Input, Image } from 'antd';
import FileUpload from '../FileUpload';
import IconFont from '@/components/IconFont';
import wx from 'weixin-js-sdk';

const { TextArea } = Input;
const alert = Modal.alert;

let statusname = {
  stalled: {
    name: '待处理',
    color: 'red',
  },
  pending: {
    name: '处理中',
    color: 'green',
  },
  completed: {
    name: '已完成',
    color: 'grey',
  },
};

class PublicList extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
      dataSource,
      isLoading: true,
      scrolltop: 0,
      refreshing: false,
      dataArr: props.dataSource || [],
      isEmpty: false,
      media_ids: [],
      curitem: {},
      params: {
        pageIndex: 1,
        is_all: 1,
        status: props.status,
        curdate: null,
      },
    };
  }

  //获取一段分页数据
  getsectiondata(np) {
    let { path, dataSource } = this.props || np;
    if (!path) {
      this.setState({
        dataSource: dataSource
          ? this.state.dataSource.cloneWithRows(dataSource)
          : this.state.dataSource,
        isLoading: false,
        refreshing: false,
        isEmpty: dataSource ? dataSource?.length == 0 : true,
      });
    } else {
      let extra = this.state.params.curdate
        ? {
            start_date: moment(this.state.params.curdate)
              .startOf('day')
              .format('YYYY-MM-DD HH:mm:ss'),
            end_date: moment(this.state.params.curdate)
              .endOf('day')
              .format('YYYY-MM-DD HH:mm:ss'),
          }
        : {};
      getFetch({
        url: path,
        params: {
          ...this.state.params,
          ...extra,
        },
      }).then((res) => {
        if (!res.data) {
          return;
        }
        let list = res?.data?.list
          ? res?.data?.list
          : res?.data?.dataList
          ? res?.data?.dataList
          : [];
        let dataArr = this.state.dataArr.concat(list);
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(dataArr),
          isLoading: false,
          refreshing: false,
          hasMore: res?.data?.hasnextpage,
          dataArr,
          isEmpty: this.state.params.pageIndex == 1 && list.length == 0,
        });
      });
    }
  }

  componentDidMount() {
    this.getsectiondata();
    getFetch({
      url: '/vehicle-api/wechat/signature',
      params: { url: document.URL },
    }).then((res) => {
      if (res.code == 0) {
        wx.config({
          debug: false,
          appId: res.data.app_id,
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonce_str,
          signature: res.data.signature,
          jsApiList: ['openLocation', 'previewImage'],
        });
        wx.ready(function () {});
        wx.error(function (err) {});
      }
    });
  }

  onRefresh = (refreshing) => {
    this.setState(
      {
        refreshing: refreshing === false ? refreshing : true,
        isLoading: refreshing === false ? refreshing : true,
        hasMore: true,
        dataArr: [],
        params: {
          ...this.state.params,
          pageIndex: 1,
          curdate: refreshing === false ? this.state.params.curdate : null,
        },
      },
      () => {
        this.getsectiondata();
      },
    );
  };

  onEndReached = (event) => {
    if (this.state.isLoading || !this.state.hasMore) {
      return;
    }
    let pageIndex = this.state.params.pageIndex + 1;
    this.setState(
      {
        isLoading: true,
        params: {
          ...this.state.params,
          pageIndex,
        },
      },
      () => {
        this.getsectiondata();
      },
    );
  };

  shouldComponentUpdate(nextProps, nextState) {
    let { dispatch } = this.props;

    if (nextState.scrolltop != this.state.scrolltop) {
      dispatch({
        type: 'global/istop',
        payload: nextState.scrolltop,
      });
      return false;
    } else {
      return true;
    }
  }

  //滚动条位置
  componentWillReceiveProps(np, ns) {
    let {
        global: { savescroll, curtype },
      } = this.props,
      npscroll = np.global.savescroll,
      nptype = np.global.curtype,
      nptop = npscroll[nptype];

    if (np.global.gotop != this.props.global.gotop) {
      this.lv.scrollTo(0, 0);
    }
    if (savescroll[curtype] != nptop && curtype != nptype) {
      this.lv.scrollTo(0, nptop);
    }
    if (np.path != this.props.path || np.status != this.props.status) {
      this.onRefresh(false);
    }
  }

  render() {
    let {
        Header,
        global: { istop },
        dispatch,
      } = this.props,
      {
        scrolltop,
        dataSource,
        isLoading,
        refreshing,
        hasMore,
        isEmpty,
        params,
      } = this.state;

    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: 'transparent',
          height: 8,
        }}
      />
    );

    const row = (row, i) => {
      return (
        <div key={row.id} className="maincard">
          <div
            className="content"
            onClick={() => {
              if (location.href.indexOf('record') != -1) {
                this.setState({
                  vs: true,
                  curitem: row,
                });
              }
            }}
          >
            <p style={{ marginBottom: 4, fontSize: 16 }} className="spacebt">
              <span>报警状态</span>
              <span
                style={{ color: statusname[row.status].color }}
                className="center"
              >
                {row.is_overtime && (
                  <>
                    <IconFont
                      type="icon-clock-filling"
                      style={{ color: 'red', marginRight: 2 }}
                    ></IconFont>
                    <span
                      style={{ color: 'red', marginRight: 8, fontSize: 14 }}
                    >
                      (超时)
                    </span>
                  </>
                )}
                {statusname[row.status].name}
              </span>
            </p>
            <div>
              {row.alarm_group_name && (
                <div className="space">
                  <span>报警类型</span>
                  <span>{row.alarm_group_name}</span>
                </div>
              )}
              {row.alarm_name && (
                <div className="space">
                  <span>用户</span>
                  <span>{row.alarm_name}</span>
                </div>
              )}
              {row.docking_floor && (
                <div className="space">
                  <span>电梯报警楼层</span>
                  <span>{row.docking_floor}</span>
                </div>
              )}
              <div className="space">
                <span>报警时间</span>
                <span>
                  {row.alarm_time
                    ? moment(row.alarm_time).format('YYYY-MM-DD HH:mm')
                    : '-'}
                </span>
              </div>

              <div className="space">
                <span>报警地点</span>
                <span>{row.alarm_address ?? '-'}</span>
              </div>
            </div>
            <div
              className="center"
              style={{
                justifyContent: 'space-between',
                paddingTop: 10,
                marginTop: 10,
                borderTop: '1px solid #f0f0f0',
              }}
              onClick={(e) => {
                e.stopPropagation();
              }}
            >
              <a
                style={{ fontSize: 16, flex: 1 }}
                onClick={() => {
                  wx.openLocation({
                    latitude: row.lat ? parseFloat(row.lat) : 22.558566, // 纬度，浮点数，范围为90 ~ -90
                    longitude: row.lng ? parseFloat(row.lng) : 114.05342, // 经度，浮点数，范围为180 ~ -180。
                    name: row.alarm_group_name, // 位置名
                    address: row.alarm_address, // 地址详情说明
                    scale: 18, // 地图缩放级别,整形值,范围从1~28。默认为最大
                    infoUrl: '', // 在查看位置界面底部显示的超链接,可点击跳转
                  });
                }}
              >
                <IconFont
                  type="icon-map1"
                  style={{ fontSize: 18, paddingRight: 4 }}
                />
                地图
              </a>
              {row.alarm_phone && (
                <a
                  style={{
                    fontSize: 16,
                    flex: 1,
                    justifyContent:
                      location.href.indexOf('record') != -1
                        ? 'flex-end'
                        : 'center',
                  }}
                  className="center"
                  onClick={() => {
                    window.open('tel:' + row.alarm_phone);
                  }}
                >
                  <IconFont
                    type="icon-phone"
                    style={{ fontSize: 16, paddingRight: 4 }}
                  />
                  拨打
                </a>
              )}
              {location.href.indexOf('record') != -1 ? null : (
                <a
                  style={{
                    fontSize: 16,
                    flex: 1,
                    display: 'flex',
                    justifyContent: 'flex-end',
                    alignItems: 'center',
                  }}
                  onClick={() => {
                    if (location.href.indexOf('record') != -1) {
                      return;
                    }
                    if (row.status == 'stalled') {
                      alert('是否处理该报警?', '点击处理，处理该条报警', [
                        { text: '取消', onPress: () => console.log('cancel') },
                        {
                          text: '处理',
                          onPress: () => {
                            putFetch({
                              url: '/vehicle-api/wechat/monitor/start_handle_monitor',
                              params: { id: row.id },
                            }).then((res) => {
                              if (res.code == 0) {
                                Toast.success('已开始处理！', 2, null, false);
                                this.onRefresh(false);
                              }
                            });
                          },
                        },
                      ]);
                    } else if (row.status == 'pending') {
                      this.setState({
                        visible: true,
                        curid: row.id,
                      });
                    }
                  }}
                >
                  <IconFont
                    type="icon-chuli"
                    style={{ fontSize: 12, paddingRight: 4 }}
                  />
                  {row.status == 'stalled' ? '处理' : '完成处理'}
                </a>
              )}
            </div>
          </div>
        </div>
      );
    };

    return (
      <div style={{ height: '100%' }}>
        <Drawer
          destroyOnClose
          title={
            <div className="spacebt">
              <span style={{ fontSize: 16 }}>处置信息</span>
            </div>
          }
          visible={this.state.vs}
          onClose={() => {
            this.setState({
              vs: false,
            });
          }}
          closable={false}
          height={'70vh'}
          placement="bottom"
        >
          <div style={{ padding: 12, fontSize: 16 }}>
            <div>
              <b>备注</b>
              <br />
              {this.state.curitem.remark}
            </div>
            <div style={{ marginTop: 12 }}>
              <b>处置照片</b>
              <div style={{ display: 'flex', flexWrap: 'wrap', marginTop: 6 }}>
                {this.state.curitem.device_alarm_images
                  ? this.state.curitem.device_alarm_images.map((it, i) => {
                      return (
                        <div
                          style={{
                            marginRight: (i + 1) % 3 == 0 ? 0 : 12,
                            marginBottom: 6,
                          }}
                          key={it.id}
                          onClick={() => {
                            wx.previewImage({
                              current: 'http://101.35.171.207' + it.path, // 当前显示图片的http链接
                              urls: this.state.curitem.device_alarm_images.map(
                                (item) => 'http://101.35.171.207' + item.path,
                              ), // 需要预览的图片http链接列表
                            });
                          }}
                        >
                          <img
                            src={it.path}
                            style={{
                              width: 'calc(33vw - 16px)',
                              height: 'calc(33vw - 16px)',
                            }}
                          />
                        </div>
                      );
                    })
                  : '暂无'}
              </div>
            </div>
          </div>
        </Drawer>

        <Drawer
          destroyOnClose
          title={
            <div className="spacebt" style={{ fontSize: 16 }}>
              <span>上传处置照片处理报警</span>
              <a
                onClick={() => {
                  if (!this.state.remark) {
                    Toast.fail('请填写备注！', 2, null, false);
                    return;
                  }
                  if (this.state.media_ids.length == 0) {
                    Toast.fail('请先选择处置照片！', 2, null, false);
                    return;
                  }

                  putFetch({
                    url: '/vehicle-api/wechat/monitor/complete_handle_monitor',
                    params: {
                      id: this.state.curid,
                      media_ids: this.state.media_ids,
                      remark: this.state.remark,
                    },
                  }).then((res) => {
                    if (res.code == 0) {
                      Toast.success('已完成处理！', 2, null, false);
                      this.onRefresh(false);
                      this.setState({
                        visible: false,
                      });
                    }
                  });
                }}
              >
                提交
              </a>
            </div>
          }
          visible={this.state.visible}
          onClose={() => {
            this.setState({
              visible: false,
            });
          }}
          closable={false}
          height={'70vh'}
          placement="bottom"
        >
          <div
            style={{
              width: '100%',
              height: '100%',
              backgroundColor: '#fff',
              padding: 12,
              position: 'relative',
            }}
            className="submitbox"
          >
            <TextArea
              rows={8}
              style={{ resize: 'none', fontSize: 16 }}
              placeholder="填写备注"
              value={this.state.remark}
              onChange={(e) => {
                this.setState({
                  remark: e.target.value,
                });
              }}
            ></TextArea>
            <FileUpload
              value={this.state.media_ids}
              onChange={(val) => {
                this.setState({
                  media_ids: val,
                });
              }}
            ></FileUpload>
          </div>
        </Drawer>
        <ListView
          ref={(el) => (this.lv = el)}
          dataSource={dataSource}
          renderHeader={() => (
            <Header
              params={params.curdate}
              changeparams={(val) => {
                this.setState(
                  {
                    params: {
                      ...this.state.params,
                      curdate: val,
                    },
                  },
                  () => {
                    this.onRefresh(false);
                  },
                );
              }}
            />
          )}
          renderFooter={() => (
            <LoadingFooter
              isLoading={isLoading && hasMore}
              isEmpty={isEmpty}
            ></LoadingFooter>
          )}
          renderRow={row}
          renderSeparator={separator}
          style={{
            overflow: 'auto',
          }}
          pageSize={10}
          onScroll={(e) => {
            this.setState({
              scrolltop: e.target.scrollTop,
            });
          }}
          scrollRenderAheadDistance={800}
          distanceToRefresh={window.devicePixelRatio * 25}
          onEndReached={this.onEndReached}
          onEndReachedThreshold={10}
          pullToRefresh={
            <PullToRefresh refreshing={refreshing} onRefresh={this.onRefresh} />
          }
        />
      </div>
    );
  }
}

export default connect(({ global, loading }) => ({
  global,
  loading,
}))(PublicList);
